{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting Thread-1\n",
      "Starting Thread-2\n",
      "Thread-1: Tue Feb 19 00:23:20 2019\n",
      "Thread-1: Tue Feb 19 00:23:21 2019\n",
      "Thread-1: Tue Feb 19 00:23:22 2019\n",
      "Thread-2: Tue Feb 19 00:23:24 2019\n",
      "Thread-2: Tue Feb 19 00:23:26 2019\n",
      "Thread-2: Tue Feb 19 00:23:28 2019\n",
      "Exiting Main Thread\n"
     ]
    }
   ],
   "source": [
    "#!/usr/bin/python\n",
    "# -*- coding: UTF-8 -*-\n",
    " \n",
    "import threading\n",
    "import time\n",
    " \n",
    "class myThread (threading.Thread):\n",
    "    def __init__(self, threadID, name, counter):\n",
    "        threading.Thread.__init__(self)\n",
    "        self.threadID = threadID\n",
    "        self.name = name\n",
    "        self.counter = counter\n",
    "    def run(self):\n",
    "        print \"Starting \" + self.name\n",
    "       # 获得锁，成功获得锁定后返回True\n",
    "       # 可选的timeout参数不填时将一直阻塞直到获得锁定\n",
    "       # 否则超时后将返回False\n",
    "        threadLock.acquire()\n",
    "        print_time(self.name, self.counter, 3)\n",
    "        # 释放锁\n",
    "        threadLock.release()\n",
    " \n",
    "def print_time(threadName, delay, counter):\n",
    "    while counter:\n",
    "        time.sleep(delay)\n",
    "        print \"%s: %s\" % (threadName, time.ctime(time.time()))\n",
    "        counter -= 1\n",
    " \n",
    "threadLock = threading.Lock()\n",
    "threads = []\n",
    " \n",
    "# 创建新线程\n",
    "thread1 = myThread(1, \"Thread-1\", 1)\n",
    "thread2 = myThread(2, \"Thread-2\", 2)\n",
    " \n",
    "# 开启新线程\n",
    "thread1.start()\n",
    "thread2.start()\n",
    " \n",
    "# 添加线程到线程列表\n",
    "threads.append(thread1)\n",
    "threads.append(thread2)\n",
    " \n",
    "# 等待所有线程完成\n",
    "for t in threads:\n",
    "    t.join()\n",
    "print \"Exiting Main Thread\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
